package com.fxcalibre.syncservices.imdb.parser;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class ImdbNameSearchParser
{
	private final static Logger log = Logger.getLogger(ImdbNameSearchParser.class.getName());

	public static List<NameResult> parse(String htmInput)
	{
		List<NameResult> result = new ArrayList<NameResult>();
		Document doc = Jsoup.parse(htmInput);
		Elements content = doc.select("table.results tr.detailed");

		for (Iterator<Element> iterator = content.iterator(); iterator.hasNext();)
		{
			log.fine("-->");
			NameResult nameResult = new NameResult();
			Element element = (Element) iterator.next();
			nameResult.setImgUrl(getFirstFound(element, "td.image img", "src"));
			nameResult.setName(getFirstFound(element, "td.name a", null));
			nameResult.setId(getFirstFound(element, "td.name a", "href"));
			nameResult.setBio(getFirstFound(element, "span.bio", null));
			nameResult.setDescription(getFirstFound(element, "span.description", null));

			result.add(nameResult);
			log.fine(nameResult.toString());

			log.fine("<--");
		}

		return result;
	}

	private static String getFirstFound(Element element, String select, String attr)
	{
		Elements elems = element.select(select);
		if (elems.size() > 0)
		{
			if (attr != null)
			{
				return elems.get(0).attr(attr);
			} else
			{
				return elems.get(0).text();
			}
		}

		return null;
	}
}
